package org.vacoor.ticket.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.vacoor.ticket.bean.SeatType;

public class ParseUtil {
	
	/**
	 * 解析座位余票信息：
	 * 一般而言,列车只能有四种座位类型(含无座),信息字符串格式如下
	 * 1*****31074*****00001*****00003*****0001
	 * 解析规则,每10位一组
	 * 1*****3107 4*****0000 1*****0000 3*****0001
	 * 第一位表示类型,
	 * 后4位置表示数量,如果<3000则为第一位类型的数量,否则为无票数量+3000
	 * 解析方式参考:https://dynamic.12306.cn/otsweb/js/order/save_passenger_info.js?version=5.42  
	 * function getTicketCountDesc(mark, seat)
	 */
	public static Map<SeatType,Integer> parseTicketStr(String str) {
		Map<SeatType, Integer> seatInfo = new HashMap<SeatType, Integer>();
		if(str.length() % 10 == 0) {
			for(int i=0;i<str.length();i+=10) {
				//获取座位信息
				String s = str.substring(i, i+10);
				//获取类型
				String type = s.substring(0,1);
				//获取数量
				int count = Integer.parseInt(s.substring(s.length()-4, s.length()));
				//对于无座,不同车无座代码不同,但是如果>3000则为无座
				if(count >= 3000) {
					System.out.println(DateUtils.formatDate(new Date(), "kk:mm:ss.SSS") + "-- 解析到:" + SeatType.NONE_SEAT + ":" + (count-3000) + "张余票");
					seatInfo.put(SeatType.NONE_SEAT, count-3000);
					continue;
				//非无座信息的处理
				}else {
					for(SeatType seat : SeatType.values()){
						//如果不是无座,无座标识和其他类型可能相同,因此在上面单独处理
						if(seat != SeatType.NONE_SEAT && seat.getValue().equals(type)) {
							System.out.println(DateUtils.formatDate(new Date(), "kk:mm:ss.SSS") + "-- 解析到:" + seat + ":" + count + "张余票");
							seatInfo.put(seat, count);
						}
					}
				}
			}
		}
		return seatInfo;
	}
	
	
	/**
	 * 处理服务器返回的JSON 如下格式
	 * {"checkHuimd":"Y","check608":"Y","msg":"","errMsg":"Y"}
	 * @param args key
	 * @return value  如果不存在key则返回""
	 */
	public static String getValueFromJsonStr(String key,String jsonContext) {
		if(!"".equals(key)) {
			Pattern p = Pattern.compile("[^{,]*" + key + "[^,}]*");
			Matcher m = p.matcher(jsonContext);
			if(m.find()){
				return m.group().replaceAll("\\s*", "").replaceAll("\"", "").replaceAll(key + ":", "");
			}
		}
		return "";
	}

	//--------------------------------------------------------------------

	/**
	 * 从html代码中解析出所有的隐藏表单域(type="hidden")
	 * 
	 * @param htmlContent
	 * @return
	 */
	public static String parseHiddenInput(String htmlContent) {
		StringBuilder sb = new StringBuilder();
		Pattern pattern = Pattern
				.compile("<input[^>]*type\\s*=\\s*[\"']*hidden[^>]*+>");
		Matcher matcher = pattern.matcher(htmlContent);
		while (matcher.find()) {
			// System.out.println(matcher.group());
			sb.append(matcher.group());
		}
		return sb.toString();
	}

	/**
	 * 将表单域的值转换为查询字符串 name=value&name=value&name=value
	 * 
	 * @param tagContent
	 * @return
	 */
	public static String parseInputTag2QueryString(String tagContent) {
		StringBuilder sb = new StringBuilder();
		Pattern pattern = Pattern.compile("<input[^>]+>");
		Matcher matcher = pattern.matcher(tagContent);
		// 匹配到一条
		while (matcher.find()) {
			String input = matcher.group();
//			System.out.println(input);
			Pattern namePattern = Pattern.compile("name\\s*=\\s*\"[^\"]+\"");
			Matcher nameMatcher = namePattern.matcher(input);
			if (nameMatcher.find()) {
				String name = nameMatcher.group().replaceAll("name\\s*=\\s*", "").replaceAll("\"", "");
//				System.out.print("名称" + name + ":");
				sb.append(name + "=");
				Pattern valuePattern = Pattern.compile("value\\s*=\\s*\"[^\"]+\"");
				Matcher valueMatcher = valuePattern.matcher(input);
				if(valueMatcher.find()) {
					String value = valueMatcher.group().replaceAll("value\\s*=\\s*", "").replaceAll("\"", "");
//					System.out.println("值" + value);
					sb.append(value);
				}
				sb.append("&");
			}
		}
		return sb.toString();
	}
	
	//移除所有的passenger的表单域(这些是手动输入的旅客信息)
	public static String removePassengerInputTag(String tagContent) {
		return tagContent.replaceAll("<input[^>]*name=\\s*.*assenger[^>]*[\"']*\\s*", "");
	}
	
	//---------------------------------------------------
	/**
	 * 格式化站点信息数组,返回List,元素为"站点名称-拼音代码-车站代码"
	 * 
	 * @param stationInfo
	 *            车站信息数组<br>
	 *            eg:<br>
	 *            [<br>
	 *            {"allPin":"","chineseName":"北京","simplePin":"BJI",
	 *            "stationTelecode":"BJP"},<br>
	 *            {"allPin":"","chineseName":"白涧","simplePin":"BJI",
	 *            "stationTelecode":"BAP"},<br>
	 *            {"allPin":"","chineseName":"宝鸡","simplePin":"BJI",
	 *            "stationTelecode":"BJY"},<br>
	 *            {"allPin":"","chineseName":"滨江","simplePin":"BJI",
	 *            "stationTelecode":"BJB"},<br>
	 *            {"allPin":"","chineseName":"北滘","simplePin":"BJI",
	 *            "stationTelecode":"IBQ"},<br>
	 *            {"allPin":"","chineseName":"碧江","simplePin":"BJI",
	 *            "stationTelecode":"BLQ"}<br>
	 *            ]
	 * @return 格式化后的信息<br>
	 *         其中每一条信息格式如下:<br>
	 *         北京-BJI-BJP
	 */
	public static List<String> parseStatioinInfo(String stationInfo) {
		// 匹配每一条记录的模式
		String stationPattern = "\\{{1}(\"[a-zA-Z]+\":\"[a-zA-Z\u4E00-\u9FA5]*\",?){4}\\}{1}";
		List<String> result = new ArrayList<String>();

		Pattern p = Pattern.compile(stationPattern);
		Matcher m = p.matcher(stationInfo);
		while (m.find()) {
			/*
			 * 拿到的每一条记录形式都为
			 * {"allPin":"","chineseName":"碧江","simplePin":"BJI","stationTelecode"
			 * :"BLQ"}
			 */
			String station = m.group();
			// 转换形式
			station = station
					.replace("{\"allPin\":\"\",\"chineseName\":\"", "")
					.replace("\",\"simplePin\":\"", "-")
					.replace("\",\"stationTelecode\":\"", "-")
					.replace("\"}", "");
			result.add(station);
		}
		return result;
	}
}
